package com.hcloud.auth.clientdetails.service.impl;

import com.hcloud.auth.clientdetails.bean.Client;
import com.hcloud.auth.clientdetails.entity.ClientEntity;
import com.hcloud.auth.clientdetails.repository.ClientRepository;
import com.hcloud.auth.clientdetails.service.ClientService;
import com.hcloud.auth.service.impl.HcloudJdbcClientDetailsService;
import com.hcloud.common.core.constants.CoreContants;
import com.hcloud.common.core.exception.ServiceException;
import com.hcloud.common.crud.service.impl.BaseDataServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Auther hepangui
 * @Date 2018/10/31
 */
@Service
public class ClientServiceImpl extends
        BaseDataServiceImpl<ClientEntity, ClientRepository, Client>
        implements ClientService {

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();


    @Override
    public void modifyPass(String id, String oldPsw, String newPsw) {

        var clientEntity = this.get(id);
        if (clientEntity == null) {
            throw new ServiceException("找不到客户端");
        }
        if (oldPsw != null && passwordEncoder.matches(oldPsw, clientEntity.getClientSecret())) {
            clientEntity.setClientSecret(passwordEncoder.encode(newPsw));
            this.update(clientEntity);
            HcloudJdbcClientDetailsService.clearCache(clientEntity.getClientId());
        } else {
            throw new ServiceException("旧密码错误");
        }
    }

    @Override
    public void resetPass(String userId) {
        if (userId == null) {
            throw new ServiceException("找不到Client");
        }
        var clientEntity = this.get(userId);
        if (clientEntity == null) {
            throw new ServiceException("找不到Client");
        }
        clientEntity.setClientSecret(passwordEncoder.encode(CoreContants.DEFAULT_PASSWORD));
        this.update(clientEntity);
        HcloudJdbcClientDetailsService.clearCache(clientEntity.getClientId());
    }

    @Override
    public ClientEntity add(ClientEntity entity) {
        if (entity != null && entity.getClientId() != null) {
            entity.setClientSecret(new BCryptPasswordEncoder().encode(CoreContants.DEFAULT_PASSWORD));
        }
        return super.add(entity);
    }

    @Override
    public Client update(Client bean) {
        var entity = this.get(bean.getId());
        if (entity == null) {
            throw new ServiceException("缺少用户id");
        }
        var password = entity.getClientSecret();
        BeanUtils.copyProperties(bean, entity);
        entity.setClientSecret(password);
        this.update(entity);
        HcloudJdbcClientDetailsService.clearCache(bean.getClientId());
        return bean;
    }

}
